package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.User;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.SimpleRedisLock;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayDeque;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //全局唯一id生成器
    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private RedissonClient redissonClient;
    //读取脚本
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    //阻塞队列
//    private BlockingQueue<VoucherOrder> orderTask = new ArrayBlockingQueue<>(1024*1024);
    //线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    //代理对象
    IVoucherOrderService proxy;

    //线程任务
    private class VoucherOrderHandler implements Runnable{
        String groupName = "stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    //从redis的stream.orders消息队列中获取信息
                    // xreadgroup group g1 c1 count 1 block 2000 streams stream.orders >
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().block(Duration.ofSeconds(2)).count(1),
                            StreamOffset.create(groupName, ReadOffset.lastConsumed())
                    );
                    //判断是否获取
                    //为空，则重新尝试获取
                    if (mapRecords == null || mapRecords.isEmpty()) {
                        continue;
                    }
                    //不为空，则开始创建订单
                    //转化为订单对象
                    MapRecord<String, Object, Object> mapRecord = mapRecords.get(0);
                    Map<Object, Object> value = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //创建订单
                    handlerVoucherOrder(voucherOrder);
                    //ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(groupName,"g1",mapRecord.getId());
                } catch (Exception e) {
                    log.error("线程出错"+e);
                    handlePendingList();
                }
            }
        }

        private void handlePendingList() {
            while (true){
                try {
                    //从redis的stream.orders消息队列的未提交确认队列中获取信息
                    // xreadgroup group g1 c1 count 1 block 2000 streams stream.orders 0
                    List<MapRecord<String, Object, Object>> mapRecords = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(groupName, ReadOffset.from("0"))
                    );
                    //判断是否获取
                    //为空，则说明无错误
                    if (mapRecords == null || mapRecords.isEmpty()) {
                        break;

                    }
                    //不为空，则开始创建订单
                    //转化为订单对象
                    MapRecord<String, Object, Object> mapRecord = mapRecords.get(0);
                    Map<Object, Object> value = mapRecord.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //创建订单
                    handlerVoucherOrder(voucherOrder);
                    //ACK确认
                    stringRedisTemplate.opsForStream().acknowledge(groupName,"g1",mapRecord.getId());
                } catch (Exception e) {
                    log.error("pending-list线程出错"+e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    }

    private void handlerVoucherOrder(VoucherOrder voucherOrder) {
        long userId = voucherOrder.getUserId();
        //获取锁(可重入),自定义锁名称
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        //尝试获取锁，设置 1秒内反复尝试获取，ttl设置为10秒
//        boolean success = lock.tryLock(1, 10, TimeUnit.SECONDS);
//      无参则使用默认值
        boolean success = lock.tryLock();
        if (!success){
            log.error("不允许重复下单");
            return;
        }

        try {
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            lock.unlock();
        }
    }

    //使用生命周期方法，在当前类创建时线程池开启线程任务
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }


    @Override
    public Result seckillVoucher(Long voucherId) {
        //用户id
        Long userId = UserHolder.getUser().getId();
        //订单id
        long orderId = redisIdWorker.nextId("order");
        //执行lua脚本，脚本中解决超卖和一人一单的问题
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(),String.valueOf(orderId)
        );
        int res = result.intValue();
        //lua返回结果不为0，没有资格
        if (res != 0){
            return Result.fail(res == 1?"1库存不足":"1不可重复下单");
        }
        //为0
        //获取代理对象，让异步操作使用
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }
    /*@Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //执行lua脚本，脚本中解决超卖和一人一单的问题
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int res = result.intValue();
        //lua返回结果不为0，没有资格
        if (res != 0){
            return Result.fail(res == 1?"1库存不足":"1不可重复下单");
        }
        //为0,将优惠卷id,用户id，订单id存等订单信息到阻塞队列中
        //新增订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long orderId = redisIdWorker.nextId("order");
        voucherOrder.setId(orderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        //把信息放到阻塞队列
        orderTask.add(voucherOrder);
        //获取代理对象，让异步操作使用
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        return Result.ok(orderId);
    }*/
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        Long userId = voucherOrder.getUserId();
        //一人一单
        //根据用户id查询数据库判断是否已下过单
        int count = query().eq("user_id", userId ).eq("voucher_id", voucherOrder.getVoucherId()).count();
        //存在
        if (count>0) {
            log.error("一人只能购买一次同一张");
            return;
        }

        //充足，库存减一
        //当库存>0进行操作
        boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0)
                .update();
        if (!success){
            log.error("库存不足");
            return;
        }
        save(voucherOrder);
    }

    /*@Override
    public Result seckillVoucher(Long voucherId) {
        //查询优惠卷信息
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);
        //查看活动是否开启
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("活动还未开始");
        }
        //查看活动是否过期
        if (voucher.getEndTime().isBefore(LocalDateTime.now())){
            return Result.fail("活动已结束");
        }
        //查看库存是否充足
        if (voucher.getStock()<1) {
            //不足，返回错误信息
            return Result.fail("库存不足");
        }


        //给用户id上锁，实现一人一单
        Long id = UserHolder.getUser().getId();
//        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order"+id,stringRedisTemplate);
//        boolean success = simpleRedisLock.tryLock(1200);
        //获取锁(可重入),自定义锁名称
        RLock lock = redissonClient.getLock("lock:order:" + id);
        //尝试获取锁，设置 1秒内反复尝试获取，ttl设置为10秒
//        boolean success = lock.tryLock(1, 10, TimeUnit.SECONDS);
//      无参则使用默认值
        boolean success = lock.tryLock();
        if (!success){
            return Result.fail("不可重复购买");
        }

        try {
            //使用事务的代理对象防止spring事务失效
            //导入aspectjweaver
            //在启动类上添加@EnableAspectJAutoProxy(exposeProxy = true)
            //才能获取到代理对象
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }

    }*/
    //封装方法来加锁
    @Transactional
    public Result createVoucherOrder(Long voucherId) {
        //一人一单
        //根据用户id查询数据库判断是否已下过单
        int count = query().eq("user_id", UserHolder.getUser().getId()).eq("voucher_id", voucherId).count();
        //存在
        if (count>0) {
            return Result.fail("一人只能购买一次同一张");
        }

        //充足，库存减一
        //当库存>0进行操作
        boolean success = seckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock",0)
                .update();
        if (!success){
            return Result.fail("库存不足");
        }
        //新增订单
        VoucherOrder voucherOrder = new VoucherOrder();
        long OrderId = redisIdWorker.nextId("order");
        voucherOrder.setId(OrderId);
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        save(voucherOrder);
        //返回订单id
        return Result.ok(OrderId);
    }
}
